﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Windows.Media;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Documents;

namespace RssBar
{
    static class Helpers
    {
        /// <summary>
        /// Pobiera dane z podanego adresu URL
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static byte[] DownloadData(string url)
        {
            byte[] downloadedData = new byte[0];
            Thread thr = new Thread(() =>
            {
                try
                {
                    WebClient wc = new WebClient();
                    downloadedData = wc.DownloadData(new Uri(url));
                }
                catch (Exception e)
                {
                    IApplication.Logger.Write(IApplication.LoggerEventType.Warning, e.Message, "[Helpers.DownloadData] Błąd podczas pobierania danych!");
                }
            });

            thr.IsBackground = true;
            thr.Start();
            thr.Join();

            return downloadedData;
        }

        /// <summary>
        /// Pobiera źródło obrazu z aplikacji
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static ImageSource GetImageSourceFromApp(string filePath)
        {
            return new ImageSourceConverter().ConvertFromString("pack://application:,,,/" + filePath) as ImageSource;
        }

        /// <summary>
        /// Pobiera źródło obrazu z podanego adresu URL
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static ImageSource GetImageSourceFromUrl(string url, DependencyObject control)
        {
            byte[] imageData = DownloadData(url);
            if (imageData != null && imageData.Length > 0)
            {
                using (MemoryStream stream = new MemoryStream(imageData))
                {
                    try
                    {
                        if (stream.Length <= 0)
                            return null;

                        BitmapFrame bf = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
                        return bf;
                    }
                    catch (Exception e)
                    {
                        IApplication.Logger.Write(IApplication.LoggerEventType.Warning, e.Message, "[Helpers.GetImageSourceFromUrl] Błąd podczas pobierania obrazu!");
                    }
                }
            }

            return null;
        }

        /// <summary>
        /// Dopasowuje tekst do podanej długości
        /// </summary>
        /// <param name="control"></param>
        /// <param name="text"></param>
        /// <param name="addAfter"></param>
        /// <param name="avaible"></param>
        /// <returns></returns>
        public static string FitText(Control control, string text, string addAfter, double avaible)
        {
            bool isTruncated = false;
            string result = string.Empty;

            FormattedText ft = new FormattedText(addAfter.Trim(),
                System.Globalization.CultureInfo.CurrentCulture,
                System.Windows.FlowDirection.LeftToRight,
                new Typeface(control.FontFamily, control.FontStyle, control.FontWeight, control.FontStretch),
                control.FontSize, control.Foreground);

            if (addAfter.Trim().Length > 0)
                avaible -= ft.Width;
            if (avaible > 0)
            {
                result = text;

                Size w = Size.Empty;
                do
                {
                    ft = new FormattedText(result,
                        System.Globalization.CultureInfo.CurrentCulture,
                        System.Windows.FlowDirection.LeftToRight,
                        new Typeface(control.FontFamily, control.FontStyle, control.FontWeight, control.FontStretch),
                        control.FontSize, control.Foreground);

                    w = new Size(ft.Width, ft.Height);

                    if (w.Width > avaible)
                    {
                        result = result.Substring(0, (int)((result.Length * avaible) / w.Width));
                        isTruncated = true;
                    }
                } while (w.Width > avaible);

                if (isTruncated && (addAfter.Trim().Length > 0))
                {
                    result += addAfter.Trim();
                }
            }
            return result;
        }

        /// <summary>
        /// Pokazuje podpowiedź nad daną kontrolką
        /// </summary>
        /// <param name="control"></param>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <param name="additional"></param>
        /// <param name="duration"></param>
        public static void ShowTooltip(DependencyObject control, int duration = 100000, bool afterRunNewLines = true, params Run[] runs)
        {
            //Tooltip
            StackPanel root = new StackPanel();
            root.Width = 300;
            {
                TextBlock tbInfo = new TextBlock();
                tbInfo.TextWrapping = TextWrapping.Wrap;
                tbInfo.TextAlignment = TextAlignment.Center;
                tbInfo.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
                tbInfo.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
                {
                    for (int i = 0; i < runs.Length; i++)
                    {
                        var run = runs[i];
                        if (afterRunNewLines && i < runs.Length - 1)
                            run.Text += Environment.NewLine + Environment.NewLine;
                        tbInfo.Inlines.Add(run);
                    }
                }

                root.Height = tbInfo.Height;
                root.Children.Add(tbInfo);
            }

            ToolTipService.SetToolTip(control, root);
            ToolTipService.SetShowDuration(control, duration);
        }
    }
}
